#!/bin/bash

debug=false
puppetcolor='--color false'
usage() {
 echo -e "Usage: applypuppet\n" >&2
 echo -e "  Options:" >&2
 echo -e "    -v, --verbose                  Print verbose debug messages\n" >&2
 exit 1
}

TEMP=$(getopt -o vc --long verbose,color -- "$@")
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

eval set -- "$TEMP"

while true ; do
    case "$1" in
        -v|--verbose) debug=true; puppetdebug='--verbose --debug';  shift ;;
        -c|--color) puppetcolor='--color true';  shift ;;
        --) shift; break ;;
        *) echo "Unknown parameter"; exit 1 ;;
    esac
done

$debug && echo "Debug mode is on"

INIT=""
LOCAL="/var/lib/puppet-local"
BRANCH="master"

mkdir -p $LOCAL

[ ! -d "$LOCAL/.git" ] && cd $LOCAL && git init && git remote add origin https://notabug.org/LiohMoeller/installbox.git && git fetch && git checkout $BRANCH && INIT="true"
cd $LOCAL
OLD_LOCAL=$(git rev-parse @)
git reset --hard
git checkout $BRANCH
git pull

NEW_LOCAL=$(git rev-parse @)
if [ "$OLD_LOCAL" = "$NEW_LOCAL" ] && [ -z "$INIT" ]; then
  1>&2 echo "git in `pwd ` is up-to-date (Version local:$OLD_LOCAL remote:$NEW_LOCAL)"
fi

puppet apply $LOCAL/puppet/installbox/site.pp --modulepath=$LOCAL/puppet/installbox/modules $puppetdebug $puppetcolor
